using System;
using System.IO;
using CodePlex.TfsLibrary.ObjectModel;
using CodePlex.TfsLibrary.RepositoryWebSvc;

namespace CodePlex.CodePlexClientLibrary
{
    [Command("revert", "Restore working copy (undo local edits)", MinArgs = 1, UsageSummary = "<path...> [options]")]
    public class RevertCommand : NonAuthenticatedCommand
    {
        bool recursive;

        [Option("recursive", "act recursively on directories", ShortName = "e")]
        public bool Recursive
        {
            get { return recursive; }
            set { recursive = value; }
        }

        public override void Execute()
        {
            foreach (string path in Arguments)
                Engine.Revert(CodePlexClientUtil.GetFullPath(path), recursive, OnSourceItem);
        }

        static void OnSourceItem(SourceItem item,
                                 SourceItemResult result)
        {
            string relativePath = CodePlexClientUtil.GetRelativePath(Directory.GetCurrentDirectory(), item.LocalName);

            if (result != SourceItemResult.S_Ok)
                ConsoleUtil.PrintCommandError(item.LocalName, result);
            else
            {
                switch (item.LocalItemStatus)
                {
                    case SourceItemStatus.Add:
                    case SourceItemStatus.Delete:
                    case SourceItemStatus.Modified:
                    case SourceItemStatus.Conflict:
                        Console.WriteLine("Reverted '{0}'", relativePath);
                        break;

                    case SourceItemStatus.Missing:
                        if (item.ItemType == ItemType.Folder)
                            Console.WriteLine("Cannot revert missing folder '{0}' (use update instead)", relativePath);
                        else
                            Console.WriteLine("Reverted '{0}'", relativePath);
                        break;

                    case SourceItemStatus.Unversioned:
                        Console.WriteLine("Skipped '{0}'", relativePath);
                        break;

                    default:
                        Console.WriteLine("Unexpected status {0} on '{1}'", item.LocalItemStatus, relativePath);
                        break;
                }
            }
        }
    }
}